/**
 * author:wos
 * time:2024-1-4
 * title:新增，修改目录权限
 */
const {makeSqlUpdate, makeSqlInsert, makeSqlSelect} = require('../../../utils/makeSql'),
    {formatTime} = require("../../../utils/timestamp")

async function edit(ctx, next) {
    let sql = ''
    const body = ctx.request.body

    //更新数据
    if (ctx.request.method === 'PUT') {
        //判断dict_type是否重复
        const rsLen = await global.query(`SELECT deptId FROM sys_dept WHERE parentId <> ${body.parentId} AND deptName = '${body.deptName}'`)
        if (rsLen.length > 0){
            global.response(ctx, {
                "status": 200,
                "code": 500,
                "data": '',
                "msg": '部门名称同级已经被使用'
            })
            return
        }

        const updateSqlConfig = {
            tableName: "sys_dept",
            noUpdateKey: ['deptId', 'createBy', 'createTime', 'version'],
            autoUpdate: {"updateBy": ctx.username, "updateTime": formatTime()},
            where: ["version", 'deptId']
        }
        sql = makeSqlUpdate(body, updateSqlConfig)


    //新建数据
    } else if (ctx.request.method === 'POST') {
        //判断dict_type是否重复
        const rsLen = await global.query(`SELECT deptId FROM sys_dept WHERE parentId = '${body.parentId}' AND deptName = '${body.deptName}'`)
        if (rsLen.length > 0){
            global.response(ctx, {
                "status": 200,
                "code": 500,
                "data": '',
                "msg": '部门名称同级已经被使用'
            })
            return
        }

        const insertSqlConfig = {
            tableName: "sys_dept",
            autoUpdate: {"createBy": ctx.username, "createTime": formatTime()},
        }
        sql = makeSqlInsert(body, insertSqlConfig)

    } else {
        global.serverError(ctx)
    }

    try {
        if (!sql) {
            global.response(ctx, {
                "status": 200,
                "code": 500,
                "data": rs,
                "msg": '参数错误'
            })
            return
        }
        let rs = await global.query(sql)
        global.response(ctx, {
            "status": 200,
            "code": 200,
            "data": rs,
            "msg": 'success'
        })
    } catch (err) {
        global.serverError(ctx)
    }
}



module.exports = edit